// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

const Player = require("Player");
const tool = require('ToolUtil');
var PlayerManager = cc.Class({
    extends: cc.Class,
    m_GamePlayer: null, //玩家类型
    m_MySelf: null, //自己玩家
    m_RecordPlayer: null, //录像中的玩家
    mPlayerNums: 0,
    mEnterGameId: 0,
    mGameAction: null, //对应的玩家动作类型
    mGameSceneMap: null, //对应的玩家游戏的类型

    ctor() {
        this.mPlayerNums = 4;
        this.mEnterGameId = 0;
        this.m_RecordPlayer = [];
        this.m_GamePlayer = [];
        this.mGameAction = {};
        this.mGameSceneMap = {};

        //直接生成好4个玩家数量

        for (var i = 0; i < 4; i++) {
            this.m_GamePlayer.push(new Player());
        }
        for (var i = 0; i < 4; i++) {
            this.m_RecordPlayer.push(new Player());
        }

    },

    registerAction(id, action) {
        this.mGameAction[id] = action;
    },

    registerScene(gameid, sceneName) {
        this.mGameSceneMap[gameid] = sceneName;
    },

    getRecordFreePlayer() {
        for (var i = 0; i < this.m_RecordPlayer.length; i++) {
            if (this.m_RecordPlayer[i].mIsFree) {
                return this.m_RecordPlayer[i];
            }
        }
        var player = new Player();
        this.m_RecordPlayer.push(player);
        return player;
    },

    getFreePlayer() {
        for (var i = 0; i < this.m_GamePlayer.length; i++) {
            if (this.m_GamePlayer[i].mIsFree) {
                return this.m_GamePlayer[i];
            }
        }
        var player = new Player();
        this.m_GamePlayer.push(player);
        return player;
    },

    createReocrdPlayer(data, gameID, showId) {
        this.m_RecordPlayer.forEach(player => {
            player.mIsFree = true;
        });
        

        data.forEach(function (element) {
            this.newRecordPlayer(element, gameID);
        }, this);

        //重新计算坐标方位
        var playerNums = this.m_RecordPlayer.length;
        if (this.m_MySelf != null && showId == null) {
            //判断有没有自己在录像里，有的话，将自己的方位修改
            var pOrd = -1;
            for (var i = 0; i < this.m_RecordPlayer.length; i++) {
                var p = this.m_RecordPlayer[i];
                if (!p.mIsFree && p.m_dbid == this.m_MySelf.m_dbid) {
                    p.m_nSeadOrd = 0; //坐位号为0
                    pOrd = p.m_btPlayOrd; //
                    p.m_headUrl = this.m_MySelf.m_headUrl;
                    tool.NetManager().mRecordMy_Self = p.m_chrID;
                    break;
                }
            }
            if (pOrd == -1) { //看的不是自己的
                pOrd = 0;
            }
            for (var i = 0; i < this.m_RecordPlayer.length; i++) {
                var p = this.m_RecordPlayer[i];
                if (p.m_btPlayOrd == pOrd)
                    continue;
                    

                p.m_nSeadOrd = p.m_btPlayOrd - pOrd;
                if (p.m_nSeadOrd <= 0) {
                    p.m_nSeadOrd = playerNums + p.m_nSeadOrd;
                } else if (p.m_nSeadOrd >= playerNums) {
                    p.m_nSeadOrd = p.m_nSeadOrd - playerNums;
                }
            }
        } else {
            //直接按playerOrd来排序
            if (showId != null && showId < playerNums) {
                var pOrd = -1;
                for (var i = 0; i < this.m_RecordPlayer.length; i++) {
                    var p = this.m_RecordPlayer[i];
                    if (p.m_chrID == showId) {
                        p.m_nSeadOrd = 0; //坐位号为0
                        pOrd = p.m_btPlayOrd;
                        tool.NetManager().mRecordMy_Self = p.m_chrID;
                        break;
                    }
                }
                if (pOrd == -1) { //看的不是自己的
                    pOrd = 0;
                }
                for (var i = 0; i < this.m_RecordPlayer.length; i++) {
                    var p = this.m_RecordPlayer[i];
                    if (p.m_btPlayOrd == pOrd)
                        continue;

                    p.m_nSeadOrd = p.m_btPlayOrd - pOrd;
                    if (p.m_nSeadOrd <= 0) {
                        p.m_nSeadOrd = playerNums + p.m_nSeadOrd;
                    } else if (p.m_nSeadOrd >= playerNums) {
                        p.m_nSeadOrd = p.m_nSeadOrd - playerNums;
                    }
                }
            } else {
                for (var i = 0; i < this.m_RecordPlayer.length; i++) {
                    var p = this.m_RecordPlayer[i];
                    p.m_nSeadOrd = p.m_btPlayOrd - 1;
                    if (p.m_nSeadOrd == 0) {
                        tool.NetManager().mRecordMy_Self = p.m_chrID;
                    }
                }
            }
        }


        // var scene = cc.director.getScene();
        // if (scene.getName() != tool.NetManager().getGameScene().toLocaleLowerCase()) {
        //     cc.director.loadScene(tool.NetManager().getGameScene().toLocaleLowerCase(), function () {


        //         var scnPly = PlayerManager.getGameScene(); 
        //         tool.NetManager().mIsPlayRecord = true;
        //         for (var i = 0; i < playerNums; i++) {
        //             var p = this.m_RecordPlayer[i];
        //             scnPly.mFace[p.m_nSeadOrd].setPlayer(p);
        //         }

        //     }.bind(this));
        // }

    },

    newRecordPlayer(data, gameid) {
        // var bRet = false;
        var player = this.getRecordFreePlayer();
        if (gameid > 0 && this.mGameAction[gameid] != null) {
            player.setGameAction(new(require(this.mGameAction[gameid])))
        }

        if (player) {
            player.init(data);
        }
        return player;

        // for (var i = 0; i < this.m_RecordPlayer.length; i++) {
        //     if (this.m_RecordPlayer[i].mIsFree) {
        //         bRet = true;
        //         this.m_RecordPlayer[i].init(data);
        //         if (gameid > 0 && this.mGameAction[gameid] != null) {
        //             this.m_RecordPlayer[i].setGameAction(new(require(this.mGameAction[gameid])))
        //         }
        //         break;
        //     }
        // }

        // // if (!bRet) {
        // //     var recordPlaer = new Player();
        // //     recordPlaer.init(data);
        // //     this.m_RecordPlayer.push(recordPlaer);
        // //     bRet = true;
        // // }
        // return bRet;
    },

    newPlayer(data, gameid) {
        if (gameid == null) {
            gameid = this.mEnterGameId;
        }
        var player = this.getFreePlayer();
        if (gameid > 0 && this.mGameAction[gameid] != null) {
            player.setGameAction(new(require(this.mGameAction[gameid])))
        }

        if (player) {
            player.init(data);
            if (this.m_MySelf == null) {
                this.m_MySelf = player;
                player.initCardCheck();
                this.sortPlayer(player);
            }
        }
        return player;
    },

    sortPlayer(player) {
        if (this.m_MySelf.m_btPlayOrd == 0) {
            if (player.m_btPlayOrd == 0) {
                player.m_nSeadOrd = -1;
            } else {
                player.m_nSeadOrd = player.m_btPlayOrd - 1;
                if (player.m_nSeadOrd < 0) {
                    player.m_nSeadOrd += PlayerManager.mPlayerNums;
                }
                if (player.m_nSeadOrd >= 0 && player.m_nSeadOrd <= this.mPlayerNums - 1) {
                    for (var idx = 0; idx < this.m_GamePlayer.length; idx++) {
                        var checkPlayer = this.m_GamePlayer[idx];
                        if (!checkPlayer.mIsFree && checkPlayer != player && checkPlayer.m_nSeadOrd == player.m_nSeadOrd) {
                            cc.log("原来座位号有人:" + checkPlayer);
                            // this.m_GamePlayer.splice(idx, 1);
                            break;
                        }
                    }
                }
            }
        } else {
            if (player.m_btPlayOrd == 0) {
                player.m_nSeadOrd = -1;
            } else {
                player.m_nSeadOrd = player.m_btPlayOrd - this.m_MySelf.m_btPlayOrd;
                if (player.m_nSeadOrd < 0) {
                    player.m_nSeadOrd += this.mPlayerNums;
                }

                if (player.m_nSeadOrd == 0 && player != this.m_MySelf) {
                    player.m_nSeadOrd++;
                }

                if (player.m_nSeadOrd >= 0 && player.m_nSeadOrd <= this.mPlayerNums - 1) {
                    for (var idx in this.m_GamePlayer) {
                        var checkPlayer = this.m_GamePlayer[idx];
                        if (!checkPlayer.mIsFree && checkPlayer != player && checkPlayer.m_nSeadOrd == player.m_nSeadOrd) {
                            cc.log("原来座位号有人:" + checkPlayer);
                            // this.m_GamePlayer.splice(idx, 1);
                            break;
                        }
                    }
                }
            }
        }
        player.m_btOffline = false;
    },

    delPlayer(player) {
        if (player == null)
            return;

        if (player.m_nSeadOrd >= 0) {
            var scnPly = this.getGameScene();
            if (scnPly)
                scnPly.leavePlayer(player);
            player.m_nSeadOrd = 0;
            player.m_boPlaying = false;
            player.m_boReady = false;
            player.mIsFree = true;
        }

        if (player == this.m_MySelf) {
            this.m_MySelf = null;
        }

        player = null;
    },

    getPlayerBySead(info, isRecord) {
        if (isRecord == null) {
            isRecord = tool.NetManager().mIsPlayRecord;
        }
        if (isRecord) {
            for (var idx in this.m_RecordPlayer) {
                if (this.m_RecordPlayer[idx].m_nSeadOrd == info && !this.m_RecordPlayer[idx].mIsFree) {
                    return this.m_RecordPlayer[idx];
                }
            }
        } else {
            for (var idx in this.m_GamePlayer) {
                if (this.m_GamePlayer[idx].m_nSeadOrd == info && !this.m_GamePlayer[idx].mIsFree) {
                    return this.m_GamePlayer[idx];
                }
            }
        }
    },

    getPlayer(info, isRecord) {
        // if (isRecord == null) {
        //     isRecord = tool.RecordManager().mIsPlayRecord;
        // }

        if (isRecord == null) {
            isRecord = false;
        }
        switch (typeof (info)) {
            case "string":
                {
                    if (isRecord) {
                        for (var idx in this.m_RecordPlayer) {
                            if (this.m_RecordPlayer[idx].m_showName == info && !this.m_RecordPlayer[idx].mIsFree) {
                                return this.m_RecordPlayer[idx];
                            }
                        }
                    } else {
                        for (var idx in this.m_GamePlayer) {
                            if (this.m_GamePlayer[idx].m_showName == info && !this.m_GamePlayer[idx].mIsFree) {
                                return this.m_GamePlayer[idx];
                            }
                        }
                    }
                }
                break;
            case "number":
                {
                    if (isRecord) {
                        for (var idx in this.m_RecordPlayer) {
                            if (this.m_RecordPlayer[idx].m_chrID == info && !this.m_RecordPlayer[idx].mIsFree) {
                                return this.m_RecordPlayer[idx];
                            }
                        }
                    } else {
                        for (var idx in this.m_GamePlayer) {
                            if (this.m_GamePlayer[idx].m_chrID == info && !this.m_GamePlayer[idx].mIsFree) {
                                return this.m_GamePlayer[idx];
                            }
                        }
                    }
                }
                break;
        }
        return null;
    },

    getPlayerByAccount(account) {
        for (var i = 0; i < this.m_GamePlayer.length; i++) {
            if (this.m_GamePlayer[i].m_szAccount == account) {
                return this.m_GamePlayer[i];
            }
        }
        return null;
    },

    clearOtherPlayer() {
        for (var i = this.m_GamePlayer.length - 1; i >= 0; i--) {
            if (this.m_GamePlayer[i] != this.m_MySelf) {
                this.delPlayer(this.m_GamePlayer[i]);
            }
        }
    },

    enterTable(data) {
        var actor = null;
        var i;
        var gameType = (data.sex >> 16);
        this.mPlayerNums = ((data.sex >> 8) & 0x0f);
        var gameID = ((data.sex >> 4) & 0x0f);

        if (gameID != 0) {
            this.mEnterGameId = gameID;
        } else {
            this.mPlayerNums = 4;
        }

        if (this.m_MySelf == null) {
            this.m_MySelf = this.getFreePlayer();
        }

        if (data.dbid == this.m_MySelf.m_dbid) {
            this.m_MySelf.init(data);
            this.clearOtherPlayer();
            if (gameID > 0 && this.mGameAction[gameID] != null) {
                this.m_MySelf.setGameAction(new(require(this.mGameAction[gameID])))
            }

            this.m_MySelf.getFunction('initCardCheck')();

            if (cc.sys.isNative && tool.getLocal() == '') {
                tool.setLocal(cc.Application.getInstance().getMapInfo());
            }


            if (tool.getLocal() != null && tool.getLocal() != "") {
                tool.NetManager().sendPacket('CSLOCAL', {
                    local: tool.getLocal()
                });
                this.m_MySelf.setAdress(myLocal);
            }

            if (this.m_MySelf.m_btPlayOrd != 0) {
                this.m_MySelf.m_nSeadOrd = 0;
                if (!this.m_MySelf.m_boReady) {
                    this.m_MySelf.showTimer(20);
                }
            } else {
                this.m_MySelf.m_nSeadOrd = -1;
            }

            if (this.m_MySelf.m_nSeadOrd < 0) {
                i = 0;
            } else {
                i = this.m_MySelf.m_nSeadOrd;
            }

            actor = this.m_MySelf;

            //得到当前游戏id对应的
            this.updateGameScene(this.mEnterGameId, gameType);

            var scene = cc.director.getScene();
            if (scene.getName() != tool.NetManager().getGameScene().toLocaleLowerCase()) {
                cc.director.loadScene(tool.NetManager().getGameScene().toLocaleLowerCase(), function () {
                    if (tool.NetManager().hasGameHandler()) {
                        tool.NetManager().unblock('SCENTERTABLE');
                    }
                }.bind(this));
            }
        } else {
            actor = this.getPlayer(data.id);
            if (actor == null) {
                actor = this.getFreePlayer();
            }
            actor.init(data);
            if (gameID > 0 && this.mGameAction[gameID] != null) {
                actor.setGameAction(new(require(this.mGameAction[gameID])))
            }

            this.sortPlayer(actor);


            var scene = cc.find('Canvas').getComponent(tool.NetManager().getGameScene());
            if (scene && scene.initWithPlayer) {
                if (actor.m_nSeadOrd >= 0 && actor.m_nSeadOrd < scene.gameFace.length) {
                    scene.gameFace[actor.m_nSeadOrd].setPlayer(actor);
                    if (scene._tableState == tool.TABLESTATE.tsStart) {
                        scene.gameFace[actor.m_nSeadOrd].setIsReady(false);
                    }
                }
                scene.initWithPlayer(actor);
            }
            tool.NetManager().unblock('SCENTERTABLE');
            // if (scene && scene.initWithPlayer) {
            //     scene.initWithPlayer(actor);
            // }

        }
        return actor;
    },

    updateGameScene(gameid, gametype) {

    },

    /**
     * 切换到游戏场景
     */
    getGameScene() {
        // return SceneManager.getSceneByCode(this.mGameSceneMap[PlayerManager.mEnterGameId]);
    },

    getGameSceneCode(id) {
        // if (id == null)
        //     id = PlayerManager.mEnterGameId;
        // return this.mGameSceneMap[id];
    },

    leaveTable(chrID) {
        var p = null;
        if (chrID == null) {
            p = this.m_MySelf;
            chrID = this.m_MySelf.m_chrID;
        } else {
            p = this.getPlayer(chrID);
            if (p == null) {
                cc.log("未找到要离开桌子的玩家 ID:" + chrID);
                return;
            }
        }
        cc.log("玩家:" + p.m_showName + " 离开桌子");
        p.leaveTable();
        if (chrID == this.m_MySelf.m_chrID) {
            if (this.m_MySelf.m_nSeadOrd >= 0) {
                this.m_MySelf.m_nSeadOrd = -1;
            }
            this.clearOtherPlayer();
            var scene = cc.director.getScene();
            if (scene.getName() != 'hall') {
                cc.director.loadScene('hall');
            }
            //  else {
            //     scene.getData('GameData.PLAYER_EXITROOMTIMEOUT')
            // }
            tool.NetManager().close();
        } else {
            this.delPlayer(p);
        }
    }
});


PlayerManager.getInstance = function () {
    if (PlayerManager.instance == null) {
        PlayerManager.instance = new PlayerManager();
    }
    return PlayerManager.instance;
};


module.exports = PlayerManager;